const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const Router = require( 'koa-router' );
const cors = require('@koa/cors');
const jwt = require('jsonwebtoken');
const { spawn } = require('child_process');
const socketioJwt = require('socketio-jwt');
const { Server } = require('socket.io')
const { createServer } = require('http')


// ------------------------------------------------------------------------------------
const router = new Router();
const app = new Koa();

// 使用 bodyParser 中间件来解析请求体
app.use(bodyParser());

// 跨域设置
app.use(cors());

// router.get('/me', (ctx, next) => {
//   // ctx.body('me接口')
//   console.log('me接口')
//   console.log('ctx', ctx)
//   ctx.body = 'hello'
// })
// 登录接口
router.post('/api/login', (ctx) => {
  const { name, password } = ctx.request.body
  const token = jwt.sign({name, password}, 'wutapp', {expiresIn: '1h'})
  ctx.body = JSON.stringify({data: token}) 
});

app.use(router.routes())
app.use(router.allowedMethods())


// ------------------------------------------------------------------------------------
const httpServer = createServer(app.callback())
const io = new Server(httpServer, {
  cors: {
    origin: "http://localhost:5173",
    methods: ["GET", "POST"],
    allowedHeaders: ["*"],
    credentials: true
  }
})
io.use(socketioJwt.authorize({
  secret: 'wutapp', // 替换为你的 JWT 密钥
  handshake: true, // 在握手阶段验证
}));

const messageList = []

io.on('connection', socket => {
  console.log('connection run...')
  // const token = socket.handshake.headers.authorization
  // console.log('user', token.substring(7))
  // 可以监听更多来自客户端的事件，例如接收消息
  socket.on('message', (data) => {
    console.log('Message received:', data);
    // 处理消息逻辑
  });

  // 监听文本消息
  socket.on('send_text_msg', data => {
    console.log('监听文本消息 ', data)
    
    // 中间逻辑
    messageList.push(data)

    // 全局广播
    io.emit('send_text_msg', data)
  })

  socket.on('send_question', question => {
    console.log('question ', question)
    // io.emit('send_text_msg', data)
    socket.emit('send_text_msg', question)

    const pythonProcess = spawn('python', ['D:/coding/toy/wuta_admin/test/ChatMiniChinese.py', question.data]);

    pythonProcess.stdout.setEncoding('utf-8');
    
    pythonProcess.stdout.on('data', (res) => {
      socket.emit('send_answer', {
        data: res,
        userId: 'admin'
      })
    });
    
    pythonProcess.stderr.on('data', (data) => {
      console.error(`Error: ${data}`);
    });
    
    pythonProcess.on('close', (code) => {
      console.log(`Child process exited with code ${code}`);
    });
  })

  // 当客户端断开连接时
  socket.on('disconnect', () => {
    console.log('A client disconnected');
  });

  socket.emit('send_text_msg', messageList)
})

const port = process.env.PORT || 8000;


// ------------------------------------------------------------------------------------
httpServer.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
})

// app.listen(port, () => {
//   console.log(`Server running at http://localhost:${port}/`);
// })